package com.wangxiaonan.wxwork.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * GET、POST 连接工具
 *
 * @Author: wangxiaonan
 * @Date: 2018/8/21
 **/
public class HttpUtil {
    private static CloseableHttpClient httpClient;

    static {
        PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
        // 最大连接数
        pcm.setMaxTotal(100);
        // 默认的每个路由的最大连接数
        pcm.setDefaultMaxPerRoute(50);
        httpClient = HttpClients.custom().setConnectionManager(pcm).build();
    }

    public static String get(String url, Map<String, String> param) throws IOException {
        if (param != null) {
            StringBuilder sb = new StringBuilder(url);
            if (!url.contains("?")) {
                sb.append("?");
            }
            for (String key : param.keySet()) {
                Object value = param.get(key);
                if (value == null) {
                    continue;
                }
                sb.append(key).append("=").append(value).append("&");
            }
            url = sb.toString().substring(0, sb.length() - 1);
        }
        return get(url);
    }

    public static String get(String url) throws IOException {
        StringBuilder result = new StringBuilder();

        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().
                setConnectTimeout(30000).
                setConnectionRequestTimeout(30000).
                setSocketTimeout(30000).build();
        httpGet.setConfig(requestConfig);
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-type", "application/json; charset=utf-8");
        httpGet.setHeader("Accept", "application/json");

        try (CloseableHttpResponse response = httpClient.execute(httpGet);
             BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
            String line;
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                result.append(line).append(NL);
            }
        }

        return result.toString();
    }

    /**
     * POST Request
     *
     * @param url
     * @param jsonString
     * @return
     */
    public static String post(String url, String jsonString) throws IOException {
        StringBuilder result = new StringBuilder("");

        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
        httpPost.setConfig(requestConfig);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(new StringEntity(jsonString, Charset.forName("UTF-8")));

        try (CloseableHttpResponse response = httpClient.execute(httpPost);
             BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                result.append(line).append(NL);
            }
        }

        return result.toString();
    }

//    public static void main(String[] args) {
//        String result = get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww6586bcd45c3483db&corpsecret=Q7bDromwj6559Rj9UKTqQrAyx522XvGA9ZSPIcLfDIw");
//        String result = get("https://qyapi.weixin.qq.com/cgi-bin/appchat/get?access_token=RWrFk6QNyOySdwQ51w_5glxD9OAvU-ptuqw97h0Zb6EaJfxu3HKKYOmM4RbBL4G5yRpxOEdFZAkv8XGbuLW8NZqPpGU8TNQ5K73wFgvjCtO0NPBgI92UbcSNx6tnLvukdfrzZTc2g1gM1fzXNVs-9Cyy0VYLzAMxPgt30KCCan5nJra7_dVKDzgWEP5Gp6JLoqBw0DaKi_YDxzYC5Ke3og&chatid=12228398891404763792");
//        System.out.println(result);

//        String jsonString = "{\n" +
//                "   \"touser\" : \"WangXiaoNan\",\n" +
//                "   \"toparty\" : \"1\",\n" +
//                "   \"totag\" : \"\",\n" +
//                "   \"msgtype\" : \"textcard\",\n" +
//                "   \"agentid\" : 1000005,\n" +
//                "   \"textcard\" : {\n" +
//                "            \"title\" : \"领奖通知\",\n" +
//                "            \"description\" : \"<div class=\\\"gray\\\">2016年9月26日</div> <div class=\\\"normal\\\">恭喜你抽中iPhone 7一台，领奖码：xxxx</div><div class=\\\"highlight\\\">请于2016年10月10日前联系行政同事领取</div>\",\n" +
//                "            \"url\" : \"URL\",\n" +
//                "            \"btntxt\":\"更多\"\n" +
//                "   }\n" +
//                "}";
//        String result = post("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=Q4ZNw__ZmyCVhpTVzwhW2APaqx40Kx69Wfe3RAdAbxGMrCxeZVRZbBPy1JFRGz_K0PT2ymI2FnSBcYI6QjR0gmv7khbA3qgP-uhrnk7TUAj3hG0d31JZHqfSMmCyjNxry39q6gSmdMszAzaEam16TmGGn_Lr49XkaBHUjBUOe_TpfwVUPOxKmdKMgqHQ4oucG5XiJc3VZFNrdHE0CQydmQ", jsonString);
//        System.out.println(result);
//    }
}
